package hk.m4s.lr.repair.test.views;

import android.app.Dialog;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.DisplayMetrics;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.TextView;

import java.util.Timer;
import java.util.TimerTask;

import hk.m4s.lr.repair.test.R;

/**
 * Created by qi.wang on 2018/1/2.
 */

public class TipsDialog extends Dialog {
    public Context context;
    Timer timer = new Timer();
    TextView negativeButton;
    private int recLen = 5;
    public TipsDialog(Context context) {
        super(context);
        this.context = context;
    }

    public TipsDialog(Context context, int theme) {
        super(context, theme);
        this.context = context;
    }

    public TipsDialog(Context context, boolean cancelable, OnCancelListener cancelListener) {
        super(context, cancelable, cancelListener);
        this.context = context;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        View view = View.inflate(context, R.layout.dialog_tips_layout, null);
        setContentView(view);
        negativeButton=(TextView)view.findViewById(R.id.negativeButton);
        setCanceledOnTouchOutside(false);
        timer.schedule(task, 1000, 1000);
        Window win = getWindow();
        WindowManager.LayoutParams lp = win.getAttributes();
        DisplayMetrics d = context.getResources().getDisplayMetrics();
        lp.width = (int) (d.widthPixels * 0.8);
        win.setAttributes(lp);

        view.findViewById(R.id.btnClose).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dismiss();
            }
        });
    }
    TimerTask task = new TimerTask() {
        @Override
        public void run() {

            recLen--;
            Message message = new Message();
            message.what = 1;
            handler.sendMessage(message);
        }
    };
    final Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg){
            switch (msg.what) {
                case 1:
                    negativeButton.setText(""+recLen+"秒后自动关闭");
                    if(recLen < 0){
                        timer.cancel();
                        dismiss();
                    }
            }
        }
    };
}
